package com.lgd.factoryattendance.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

/**
 * @Author lgd
 * @Date 2024/4/22 13:05
 *   activity 基类 设置长时间不操作返回 屏保界面
 */
public abstract class BaseActivity extends AppCompatActivity {

    private static final int NO_TOUCH_INTERVAL = 15 * 60 *1000; // 息屏时间
    private static final String TAG = "BaseActivity";
    private Handler noTouchHandler;
    private Runnable noTouchRunnable;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化Handler和Runnable
        noTouchHandler = new Handler(Looper.getMainLooper());
        noTouchRunnable = new Runnable() {
            @Override
            public void run() {
//                startLockScreenActivity();
            }
        };

        // 监听触摸事件
        getWindow().getDecorView().setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 用户触摸屏幕时重置定时器
                Log.d(TAG, "------ 触摸屏幕 ------");
                resetNoTouchTimer();
                return false;
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        // Activity恢复时开始定时器
        startNoTouchTimer();
    }

    @Override
    protected void onPause() {
        super.onPause();
        // Activity暂停时移除定时器
        removeNoTouchTimer();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 清除Handler和Runnable
        removeNoTouchTimer();
        noTouchHandler = null;
        noTouchRunnable = null;
    }

    private void startNoTouchTimer() {
        noTouchHandler.postDelayed(noTouchRunnable, NO_TOUCH_INTERVAL);
    }

    private void resetNoTouchTimer() {
        removeNoTouchTimer();
        startNoTouchTimer();
    }

    private void removeNoTouchTimer() {
        noTouchHandler.removeCallbacks(noTouchRunnable);
    }

    // 提供屏保Activity的默认启动方法，子类可以覆盖它
    protected void startLockScreenActivity() {
        Intent intent = new Intent(this, ScreensaverActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }
}
